/**
 * Copyright 2016 vip.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * </p>
 **/

package spring.cloud.tasks.tasks_manager.database.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import spring.cloud.tasks.tasks_manager.database.entity.NameSpaceDto;
import spring.cloud.tasks.tasks_manager.database.repository.NameSpaceDtoRepository;
import spring.cloud.tasks.tasks_manager.database.service.NameSpaceDtoService;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author timmy.hu
 */
@Service
public class NameSpaceDtoServiceImpl implements NameSpaceDtoService {

    private static final Logger log = LoggerFactory.getLogger(NameSpaceDtoServiceImpl.class);

    private static final int BATCH_NUM = 2000;

    @Autowired
    private NameSpaceDtoRepository nameSpaceDtoRepository;

    @Override
    public NameSpaceDto selectByNameSpace(String namespace) {
        return nameSpaceDtoRepository.selectByNamespace(namespace);
    }

    @Override
    public List<NameSpaceDto> selectAll() {
        return nameSpaceDtoRepository.selectAll();
    }

    @Override
    public List<NameSpaceDto> selectAll(List<String> list) {
        return nameSpaceDtoRepository.selectAllByNamespaces(list);
    }

    @Transactional
    @Override
    public void create(NameSpaceDto namespaceInfo) {
        nameSpaceDtoRepository.insert(namespaceInfo);
    }

    @Override
    public void update(NameSpaceDto namespaceInfo) {
        nameSpaceDtoRepository.update(namespaceInfo);
    }

    @Transactional
    @Override
    public int deleteByNamespace(String namespace) {
        return nameSpaceDtoRepository.deleteByNamespace(namespace);
    }

    @Transactional
    @Override
    public void deleteAll() {
        int deleteNum = 0;
        while (true) {
            deleteNum = nameSpaceDtoRepository.batchDelete(BATCH_NUM);
            if (deleteNum < BATCH_NUM) {
                return;
            }
            try {
                TimeUnit.MILLISECONDS.sleep(50);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

}
